<template>
  <a-modal
    v-model:visible="dataModel.visible"
    :mask-closable="false"
    :ok-loading="loading"
    :on-before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-form
        ref="tenantModalForm"
        layout="vertical"
        :model="formData"
        :disabled="dataModel.disabled"
        :style="{width:'100%'}">
        <a-form-item
          :disabled="dataModel.type !== Operation.CREATE"
          field="tenantId"
          label="租户id"
          :rules="[{required: true, message:'请输入租户id'}]">
          <a-input v-model="formData.tenantId" placeholder="请输入租户id..." allow-clear />
        </a-form-item>
        <a-form-item
          field="name"
          label="租户名"
          :rules="[{required: true, message:'请输入租户名'}]">
          <a-input v-model="formData.name" placeholder="请输入租户名..." allow-clear />
        </a-form-item>
        <a-form-item
          field="logo"
          label="LOGO">
            <e-upload-image v-model:url="formData.logo" :show-file-list="false" :width="150" :height="150"/>
        </a-form-item>
        <a-form-item field="enabled" label="状态">
          <a-switch
            v-model:model-value="formData.enabled"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              正常
            </template>
            <template #unchecked>
              异常
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item
          field="time"
          label="租用时间"
        >
          <a-range-picker
            v-model="timeRange"
            style="width: 360px; margin: 0 24px 24px 0;"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import useLoading from '@/hooks/loading'
import useDataModel from "@/hooks/data-model";
import dayjs from 'dayjs'
import { ValidatedError } from '@arco-design/web-vue/es/form/interface'
import { Message } from "@arco-design/web-vue";
import { create, findById, update } from "@/api/modules/system/tenant";
import { Operation, TimeRanger } from "@/types/global";
import type { TenantDto } from '@/types/modules/system'
import EUploadImage from "@/components/e-upload-image.vue";

const defaultFormData = (): TenantDto => ({
  enabled: true
})
const tenantModalForm = ref<any>(null)
const formData = ref<TenantDto>(defaultFormData())
const timeRange = ref<TimeRanger>(['', ''])
const { dataModel, openModel, closeModel } = useDataModel()
const { loading, setLoading } = useLoading()
const emit = defineEmits(["refresh"]);

const handleCancel = () => {
  closeModel()
  formData.value = defaultFormData()
  timeRange.value = ['', '']
  setLoading(false)
}

const createHandle = async () => {
  openModel('添加租户信息', false, true, Operation.CREATE)
}

const updateHandle = async (id: number) => {
  const { data } = await findById(id)
  formData.value = {
    ...data
  }
  timeRange.value = [dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss'), dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')]
  openModel('编辑租户信息', false, true, Operation.UPDATE)
}

const previewHandle = async (id: number) => {
  const { data } = await findById(id)
  formData.value = {
    ...data
  }
  timeRange.value = [dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss'), dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')]
  openModel('预览租户信息', true, false, Operation.PREVIEW)
}

const handleOk = async (done: (closed: boolean) => void) => {
  if (dataModel.submit) {
    [formData.value.startTime, formData.value.endTime] = timeRange.value
    setLoading(true);
    if (tenantModalForm.value) {
      await tenantModalForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          try {
            if(dataModel.type === Operation.CREATE) {
              await create(formData.value)
              Message.success({
                content: "添加成功",
                duration: 2000
              });
            } else if (dataModel.type === Operation.UPDATE) {
              await update(formData.value)
              Message.success({
                content: "修改成功",
                duration: 2000
              });
            }
            handleCancel()
            emit("refresh");
          } catch (e) {
            done(false)
          }
          done(false)
        } else {
          setTimeout(() => {
            setLoading(false)
          }, 2000)
          done(false)
        }
      })
    }
  }
}

defineExpose({ createHandle, updateHandle, previewHandle })
</script>

<script lang="ts">
export default {
  name: 'TenantModal'
}
</script>

<style scoped>

</style>
